package com.itxialu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itxialu.reggie.common.CustomException;
import com.itxialu.reggie.entity.Category;
import com.itxialu.reggie.entity.Dish;
import com.itxialu.reggie.entity.Setmeal;
import com.itxialu.reggie.mapper.CategoryMapper;
import com.itxialu.reggie.service.CategoryService;
import com.itxialu.reggie.service.DishService;
import com.itxialu.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 1 菜品分类 2 套餐分类
 *
 * @author shkstart
 * @create 2022-10-02 19:51
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;//菜品

    @Autowired
    private SetmealService setmealService;//套餐

    //根据id删除分类，删除前判断是否关联
    @Override
    public void remove(long ids) {

        //1.查询当前分类是否关联了菜品，如果已经关联，抛出业务异常
        LambdaQueryWrapper<Dish> dishwrapper = new LambdaQueryWrapper<>();

        dishwrapper.eq(Dish::getCategoryId, ids);
        int count = dishService.count(dishwrapper);//count:统计数据量
        if (count > 0) {
            //已关联了菜品，抛出异常
            throw new CustomException("当前套餐下已关联了" + count + "个菜品，不能删除！");
        }
        //2.查询当前分类是否关联了套餐，如果已经关联，抛出业务异常
        LambdaQueryWrapper<Setmeal> Setmealwrapper = new LambdaQueryWrapper<>();

        Setmealwrapper.eq(Setmeal::getCategoryId, ids);
        int count1 = setmealService.count(Setmealwrapper);
        if (count1 > 0) {
            //已关联了套餐，抛出异常
            throw new CustomException("当前套餐下已关联了" + count1 + "个套餐，不能删除！");
        }
        //3.正常删除
        super.removeById(ids);
    }
}
